package com.yanqu.road.dao.impl.servercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ProcessInfo;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ProcessInfoDaoImpl extends TempDao {

	public List<ProcessInfo> getServerProcessInfo(int serverId) {

		ResultSet rs = null;
		CallableStatement call = null;
		List<ProcessInfo> list = new ArrayList<>();

		String sql = "select * from t_s_process where serverId=?";
		try {
			getDb().setConnName(DbNameStrategy.getServerDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setInt(1, serverId);
			rs = call.executeQuery();
			while (rs.next()) {
				ProcessInfo gameServerInfo = parseProcessInfo(rs.getString("gameServerInfo"), rs.getInt("serverId"));
				ProcessInfo webServerInfo = parseProcessInfo(rs.getString("webServerInfo"), rs.getInt("serverId"));
				ProcessInfo agentServerInfo = parseProcessInfo(rs.getString("agentServerInfo"), rs.getInt("serverId"));

				list.add(gameServerInfo);
				list.add(webServerInfo);
				list.add(agentServerInfo);
				return list;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return list;
	}

	private ProcessInfo parseProcessInfo(String infoStr, int serverId) {
		ProcessInfo data = new ProcessInfo();
		data.setServerId(serverId);

		JSONObject jObject = JSONObject.parseObject(infoStr);
		data.setServerName(jObject.getString("serverName"));
		data.setServerIndex(jObject.getIntValue("serverIndex"));
		data.setName(jObject.getString("name"));
		data.setAddress(jObject.getString("address"));
		data.setPort(jObject.getIntValue("port"));
		data.setAdminPort(jObject.getIntValue("adminPort"));
		return data;
	}
}
